<template>
    <view class="page-container" :class="{ 'page-loaded': pageLoaded }">
        <!-- 顶部背景图区域 -->
        <view class="top-bg-section" :style="{ backgroundImage: `url(${topBgImage})` }">
            <view class="back-btn" @click="goBack">
                <image class="back-image" src="https://zero-one01.oss-cn-shenzhen.aliyuncs.com/icon/back.png"
                    mode="scaleToFill"></image>
            </view>

            <!-- 左下角配置预览图片 -->
            <view class="reconfigure-preview">
                <image class="preview-image" src="https://zero-one01.oss-cn-shenzhen.aliyuncs.com/icon/peizhiyulanwenzi.png"
                    mode="scaleToFill"></image>
            </view>

            <!-- 右下角重新配置按钮 -->
            <view class="reconfigure-btn" @click="goBack">
                <text class="btn-text">重新配置</text>
            </view>
        </view>

        <!-- 配置信息区域 -->
        <view class="material-section" :class="{ 'section-transition': tabChanging }">
            <view class="configuration-item">
                <text class="item-label">球杆版本</text>
                <view class="item-value justify-between">
                    <text class="version-name">ZERO ONE 手工杆</text>
                    <text class="version-price">¥{{ totalPrice }}</text>
                </view>
                <view class="item-value justify-between">
                    <text class="version-name">定金</text>
                    <!-- 定金输入框（带金额校验和格式化） -->
                    <input class="version-price input-control" type="number" placeholder="请输入定金金额" v-model="formattedDeposit"
                        @input="handleDepositInput" @blur="formatDeposit" />
                    <!-- 错误提示 -->
                    <text v-if="depositError" class="error-message">{{ depositError }}</text>
                </view>
            </view>

            <view class="configuration-item">
                <text class="item-label">购杆信息</text>
                <view class="item-value justify-between">
                    <text class="version-name">购杆人</text>
                    <input class="version-price input-control" type="text" placeholder="请输入姓名" v-model="buyerName" />
                </view>
                <view class="item-value justify-between">
                    <text class="version-name">联系方式</text>
                    <!-- 联系方式输入框（带实时校验） -->
                    <input class="version-price input-control" type="tel" placeholder="请输入手机号" v-model="phoneNumber"
                        maxlength="11" @input="validatePhone" />
                    <!-- 手机号错误提示 -->
                    <text v-if="phoneError" class="error-message">{{ phoneError }}</text>
                </view>
                <view class="item-value justify-between">
                    <text class="version-name">地址</text>
                    <input class="version-price input-control" type="text" placeholder="请输入地址" v-model="address" />
                </view>
            </view>

            <view class="configuration-item">
                <text class="item-label">门店信息</text>
                <view class="item-value justify-between">
                    <text class="version-name">零售门店</text>
                    <text class="version-price">ZERO ONE台球用品旗舰店</text>
                </view>
            </view>

            <!-- 内容区域 -->
            <view class="content-container bg-gray-1 rounded-lg p-4">
                <text class="title">下单须知</text>
                <text class="message"> <text class="special-text">订单锁单后，</text>桌球杆安排生产，配置等工作，桌球杠所以人订单信息无法再修改<text
                        class="special-text">定金不退。</text></text>
            </view>

            <!-- 立即支付按钮 -->
            <view class="form-item">
                <view class="proxy-pay-btn" @click="submitReservation">
                    <text class="proxy-pay-text">立即支付</text>
                </view>
            </view>
            <!-- 发起代付按钮（灰色样式） -->
            <view class="form-item">
                <view class="proxy-pay-btn" @click="faqipay">
                    <text class="proxy-pay-text">发起代付</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import sheep from '@/sheep';

export default {
    data() {
        return {
            topBgImage: 'https://zero-one01.oss-cn-shenzhen.aliyuncs.com/app/flower/f1-thumb.png',
            currentTab: 'configuration',
            pageLoaded: false,
            tabChanging: false,
            btnClicked: false,
            totalPrice: '¥1,000',
            originalPrice: '1,488',

            // 表单数据
            rawDeposit: '',       // 原始定金数值（未格式化）
            formattedDeposit: '', // 格式化后的定金显示
            buyerName: '',        // 购杆人
            phoneNumber: '',      // 联系方式
            address: '',          // 地址

            // 错误提示
            depositError: '',
            phoneError: '',
            configData: '',
            skuList: [],
            orderSN: ''
        };
    },
    created() {
        this.configData = uni.getStorageSync('selectedConfig');
        if (this.configData) {
            this.totalPrice = this.configData.currentFinalPrice;
            this.originalPrice = this.configData.currentOriginalPrice;
            
            // 处理铭牌（单个）
            this.configData.mingpai.quantity = 1;
            this.configData.mingpai.skuId = this.configData.mingpai.id;
            this.skuList.push(this.configData.mingpai);

            // 处理前肢（单个）
            this.configData.qianzhi.quantity = 1;
            this.configData.qianzhi.skuId = this.configData.qianzhi.id;
            this.skuList.push(this.configData.qianzhi);

            // 处理插花规格（单个）
            this.configData.guige.quantity = 1;
            this.configData.guige.skuId = this.configData.guige.id;
            this.skuList.push(this.configData.guige);

            // 处理插花木料（多个，数组形式）
            if (Array.isArray(this.configData.flower)) {
                this.configData.flower.forEach(flowerItem => {
                    flowerItem.quantity = 1; // 每个插花木料数量为1
                    flowerItem.skuId = flowerItem.id; // 绑定skuId
                    this.skuList.push(flowerItem); // 逐个添加到skuList
                });
            } else {
                // 兼容旧数据（如果不是数组，按单个处理）
                this.configData.flower.quantity = 1;
                this.configData.flower.skuId = this.configData.flower.id;
                this.skuList.push(this.configData.flower);
            }
        }
        console.log('获取配置信息:', this.configData);
        console.log('构建的skuList:', this.skuList);
    },
    methods: {
        // 处理定金输入（实时过滤非数字字符）
        handleDepositInput(e) {
            // 移除所有非数字字符（保留小数点后两位）
            let value = e.detail.value.replace(/[^\d.]/g, '');
            // 限制只能有一个小数点
            value = value.replace(/\.{2,}/g, '.');
            // 限制小数点后最多两位
            value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            // 移除开头的0（除了0.xx的情况）
            if (value.startsWith('0') && value.length > 1 && !value.startsWith('0.')) {
                value = value.substring(1);
            }

            this.rawDeposit = value;
            this.formattedDeposit = value;
            this.depositError = '';
        },

        // 格式化定金为金额格式（失去焦点时）
        formatDeposit() {
            if (!this.rawDeposit) {
                this.formattedDeposit = '';
                this.depositError = '';
                return;
            }

            // 验证金额有效性
            const num = parseFloat(this.rawDeposit);
            if (isNaN(num) || num <= 0) {
                this.depositError = '请输入有效的金额';
                return;
            }

            // 格式化金额为带千分位的格式
            this.formattedDeposit = '¥' + num.toLocaleString('zh-CN', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2
            });
        },

        // 验证手机号格式（实时校验）
        validatePhone() {
            const phone = this.phoneNumber;
            if (!phone) {
                this.phoneError = '';
                return;
            }

            // 手机号正则：1开头，第二位3-9，后面9位数字
            const phoneReg = /^1[3-9]\d{9}$/;

            if (phone.length < 11) {
                this.phoneError = '请输入11位手机号';
            } else if (!phoneReg.test(phone)) {
                this.phoneError = '手机号格式不正确';
            } else {
                this.phoneError = '';
            }
        },

        goBack() {
            uni.navigateBack();
        },

        handleOrder() {
            if (!this.btnClicked) {
                uni.navigateTo({
                    url: '/pages/index/confirmOrder'
                });
                return;
            }

            this.btnClicked = true;
            setTimeout(() => {
                this.btnClicked = false;
            }, 200);
        },

        submitReservation() {
            // 发起支付前验证
            if (!this.rawDeposit) {
                this.depositError = '请输入定金金额';
                return;
            }
            if (!this.phoneNumber || !/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
                this.phoneError = '请输入正确的手机号';
                return;
            }
            if (!this.buyerName || !this.address) {
                uni.showToast({ title: '请完善所有信息', icon: 'none', duration: 2000 });
                return;
            }

            // 调用创建订单方法
            this.submitOrder().then(() => {
                uni.navigateTo({
                    url: `/pages/index/shouyintai?orderSN=${this.orderSN || 1}&totalAmount=${this.rawDeposit || 1}`
                });
            }).catch((error) => {
                console.error('创建订单失败:', error);
                uni.showToast({ title: '创建订单失败', icon: 'none', duration: 2000 });
            });
        },

        faqipay() {
            // 发起代付前验证（同立即支付）
            if (!this.rawDeposit) {
                this.depositError = '请输入定金金额';
                return;
            }
            if (!this.phoneNumber || !/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
                this.phoneError = '请输入正确的手机号';
                return;
            }
            if (!this.buyerName || !this.address) {
                uni.showToast({ title: '请完善所有信息', icon: 'none', duration: 2000 });
                return;
            }

            // 调用创建订单方法
            this.submitOrder().then(() => {
                uni.navigateTo({
                    url: `/pages/index/shouyintai?orderSN=${this.orderSN || 1}&totalAmount=${this.rawDeposit || 1}`
                });
            }).catch((error) => {
                console.error('创建订单失败:', error);
                uni.showToast({ title: '创建订单失败', icon: 'none', duration: 2000 });
            });
        },

        // 解析spData的通用方法（提取规格信息）
        parseSpData(item, key) {
            if (item && item.spData) {
                try {
                    const spData = JSON.parse(item.spData);
                    return spData[key] || '未知';
                } catch (error) {
                    console.error('解析spData出错:', error);
                    return '未知';
                }
            }
            return '未知';
        },

        // 创建订单（适配多个插花木料）
        submitOrder() {
            // 提取球杆参数（长度、皮头直径等）
            const length = this.configData.length || '未设置';
            const tipDiameter = this.configData.tipDiameter || '未设置';
            const gripCircumference = this.configData.gripCircumference || '未设置';
            const weight = this.configData.weight || '未设置';
            const balancePosition = this.configData.balancePosition || '未设置';

            // 提取所有插花木料的名称（适配数组）
            let flowerNames = [];
            if (Array.isArray(this.configData.flower)) {
                flowerNames = this.configData.flower.map(flowerItem => {
                    return this.parseSpData(flowerItem, '插花木料');
                });
            } else if (this.configData.flower) {
                // 兼容单个插花木料的情况
                flowerNames.push(this.parseSpData(this.configData.flower, '插花木料'));
            }
            const flowerText = flowerNames.length > 0 ? flowerNames.join('、') : '无';

            return new Promise((resolve, reject) => {
                // 订单备注：包含球杆参数和所有插花木料
                const note = `
                    皮头直径：${tipDiameter}，
                    长度：${length}，
                    握把：${gripCircumference}，
                    重量：${weight}，
                    重心位置：${balancePosition}，
                    插花木料：${flowerText}
                `.replace(/\s+/g, ' ').trim(); // 去除多余空格

                const params = {
                    note: note,
                    receiverPhone: this.phoneNumber,
                    receiverName: this.buyerName,
                    receiverDetailAddress: this.address,
                    payAmount: this.rawDeposit,
                    payType: 2,
                    skuList: this.skuList, // 已包含多个插花木料的sku
                };
                console.log('订单参数:', params);

                sheep.$api.order.create(params).then((res) => {
                    console.log('订单创建成功，订单号:', res);
                    this.orderSN = res;
                    resolve();
                }).catch((error) => {
                    console.error('创建订单接口失败:', error);
                    reject(error);
                });
            });
        }
    },
    mounted() {
        setTimeout(() => {
            this.pageLoaded = true;
        }, 100);
    }
};
</script>

<style scoped>
/* 页面容器 */
.page-container {
    background-color: #1a1a1a;
    color: white;
    min-height: 100vh;
    overflow-x: hidden;
    opacity: 0;
    transition: opacity 0.5s ease;
}

.page-container.page-loaded {
    opacity: 1;
}

/* 顶部背景区域 */
.top-bg-section {
    position: relative;
    background-size: cover;
    background-position: center;
    height: 40vh;
    min-height: 300px;
    max-height: 500px;
}

.back-btn {
    position: absolute;
    top: 80rpx;
    left: 20rpx;
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.back-image {
    width: 80rpx;
    height: 80rpx;
    object-fit: contain;
}

.reconfigure-preview {
    position: absolute;
    bottom: 20px;
    left: 20px;
    width: 360rpx;
    height: 90rpx;
    border-radius: 12rpx;
    overflow: hidden;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.reconfigure-btn {
    position: absolute;
    bottom: 20px;
    right: 20px;
    padding: 12rpx 24rpx;
    border-radius: 24rpx;
    background-color: rgba(255, 255, 255, 0.1);
    font-size: 16px;
}

/* 配置信息 */
.material-section {
    padding: 20px;
}

.configuration-item {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #333;
}

.item-label {
    font-size: 16px;
    color: #999;
    margin-bottom: 10px;
    display: block;
}

.item-value {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-top: 15px;
    flex-wrap: wrap;
    /* 允许错误提示换行 */
}

/* 使内容两端对齐的类 */
.justify-between {
    justify-content: space-between;
}

.version-name {
    font-size: 16px;
    font-weight: 500;
}

.version-price {
    font-size: 16px;
    font-weight: 500;
    text-align: right;
}

/* 输入框样式 */
.input-control {
    width: 50%;
    padding: 8rpx 12rpx;
    border-radius: 6rpx;
    color: #fff;
    border: 1px solid transparent;
}

.input-control::placeholder {
    color: #666;
    font-size: 14px;
}

.input-control:focus {
    border-color: #666;
    outline: none;
}

/* 错误提示样式 */
.error-message {
    width: 100%;
    color: #ff4d4f;
    font-size: 12px;
    margin-top: 5px;
    text-align: right;
    padding-right: 0;
}

/* 内容区域 */
.content-container {
    margin: 20px 0;
    background-color: #2d2b2b;
}

.title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 10px;
    display: block;
    color: white;
}

.message {
    font-size: 14px;
    line-height: 1.5;
    color: #ccc;
}

/* 灰色背景 */
.bg-gray-1 {
    background-color: #2d2b2b;
}

/* 圆角 */
.rounded-lg {
    border-radius: 12rpx;
}

/* 内边距 */
.p-4 {
    padding: 16rpx;
}

/* 立即支付按钮样式 */
.reservation-btn-image {
    width: 560rpx;
    height: 80rpx;
    object-fit: contain;
    cursor: pointer;
    transition: transform 0.2s;
}

.reservation-btn-image:active {
    transform: scale(0.95);
}

/* 发起代付按钮样式（灰色调） */
.proxy-pay-btn {
    width: 560rpx;
    height: 80rpx;
    background-color: #444;
    /* 深灰色背景 */
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid #555;
    /* 灰色边框 */
}

.proxy-pay-btn:active {
    background-color: #555;
    /* 点击时略亮 */
    transform: scale(0.95);
}

.proxy-pay-text {
    color: #ccc;
    /* 浅灰色文字 */
    font-size: 30rpx;
    font-weight: 500;
}

.form-item {
    display: flex;
    justify-content: center;
    margin: 15px 0;
}

.special-text {
    color: chocolate;
}
</style>